package com.boarsoft.boar.demo.order.biz;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.demo.constant.OrderConstant;
import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.user.entity.PocAccount;
import com.boarsoft.common.Util;
import com.boarsoft.common.biz.SimpleBizImpl;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.common.util.RandomUtil;
import com.boarsoft.dao.sharding.bean.DaoSharding;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.core.Messenger;

@Component("orderBiz")
public class PocOrderBizImpl extends SimpleBizImpl implements PocOrderBiz {

	private static final Logger log = LoggerFactory.getLogger(PocOrderBizImpl.class);

	private static final String dateFormate = "yyyy-MM-dd HH:mm:ss";

	@Override
	@Transactional
	@DaoSharding(policy = "user", index = 0)
	public boolean save(int tenantId, PocOrder order) {

		if (dao.save(order) == null) {
			return false;
		}
		return true;
	}

	@Override
	@Transactional
	@DaoSharding(policy = "user", index = 0)
	public boolean update(int tenantId, PocOrder order) {
		return dao.update(order);
	}

	@Override
	@Transactional(readOnly = true)
	@DaoSharding(policy = "user", index = 0)
	public PocOrder findById(int tenantId, int orderId) {
		// tenantId仅作为分片参数，不用于查询
		return dao.get(PocOrder.class, orderId);
	}

	@Override
	@Transactional
	@DaoSharding(policy = "user", index = 0)
	public boolean placeOrder(int tenantId, PocAccount account, PocOrder order) {

		boolean flag = false;
		flag = dao.update(account);
		Object pocOrder = dao.save(order);

		if (flag == false || pocOrder == null) {
			return false;
		}

		return true;
	}

	@Override
	@Transactional
	@DaoSharding(policy = "user", index = 0)
	public void payOrder(int tenantId, PocOrder order, PocAccount account, boolean callType) throws Exception {

		// 设置订单状态
		order.setStatus(OrderConstant.FINISH_STS.getCode());
		order.setModifyTime(new SimpleDateFormat(dateFormate).format(new Date()));

		dao.update(account);
		dao.update(order);
		// 支付成功，发消息扣减库存
		Message m = new Message();
		m.setTarget("productTransaction");
		m.addRecipient("productTransactionSvc");
		m.setContent(order);
		m.setId(RandomUtil.genUUID());
		try {
			Messenger.send(m);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("消息发送失败..." + order.getOrderId());
		}

		if (callType) {
			throw new RuntimeException("测试事务例外");
		}

	}

	@Override
	@Transactional(readOnly = true)
	@DaoSharding(policy = "user", index = 0)
	public PagedResult<PocOrder> listByOrderIdAndUserId(int tenantId, int orderId, int userId, String orderBy, int pageNo,
			int pageSize) {

		// 默认查询第一页10条记录
		if (pageNo == 0) {
			pageNo = 1;
		}
		if (pageSize == 0) {
			pageSize = 10;
		}

		StringBuilder sb = new StringBuilder();

		if (orderId != 0) {
			sb.append(" and order_id = " + orderId);
		}
		if (userId != 0) {
			sb.append(" and user_id = " + userId);
		}

		int total = dao.getTotal(PocOrder.class, sb.toString());

		if (Util.strIsNotEmpty(orderBy)) {
			sb.append(" order by ").append(orderBy);
		}

		List<PocOrder> orders = dao.list(PocOrder.class, sb.toString(), pageNo, pageSize);

		return new PagedResult<PocOrder>(total, orders, pageNo, pageSize);

	}

	// @Override
	// @Transactional
	// @DaoSharding(policy = "user", index = 0)
	// public boolean cancelOrder(int tenantId, PocOrder order) {
	//
	// // 查询订单信息
	// order = this.findById(order.getTenantId(), order.getOrderId());
	//
	// // 释放锁定账户金额
	// PocAccount userAccount = pocAccountService.find(order.getTenantId(),
	// order.getUserId());
	//
	// if (userAccount != null) {
	// userAccount.setLockAmount(userAccount.getLockAmount() -
	// order.getAmount());
	// userAccount.setAvailableAmount(userAccount.getAvailableAmount() +
	// order.getAmount());
	// } else {
	// log.error("账户异常...");
	// return false;
	// }
	//
	// // 3.锁定库存状态更新,释放锁定库存
	// PocProduct product = productServ.find(order.getProductId());
	// if (product != null) {
	//
	// // 撤单，发消息扣减库存
	// Message m = new Message();
	// m.setTarget("productTransaction");
	// m.addRecipient("productTransactionSvc");
	// m.setContent(order);
	// m.setId(RandomUtil.genUUID());
	// try {
	// Messenger.send(m);
	// } catch (Exception e) {
	// e.printStackTrace();
	// log.error("消息发送失败..." + order.getOrderId());
	// }
	// } else {
	// log.error("产品异常...");
	// return false;
	// }
	//
	// // 设置订单状态
	// order.setStatus(OrderConstant.CANCEL_STS.getCode());
	// order.setModifyTime(new SimpleDateFormat(dateFormate).format(new
	// Date()));
	//
	// pocAccountService.update(tenantId, userAccount);
	// this.save(tenantId, order);
	//
	// return true;
	//
	// }
}
